import React, { useEffect, useState } from 'react'
import request from '../utils/request'
import styles from '../style/files.module.less'
import { message, Table } from 'antd'
import { CopyOutlined, DownloadOutlined } from '@ant-design/icons';

const { Column } = Table;

interface DataType {
  id: React.Key;
  md5: string;
  file_name: string;
  mimetype: string;
  size: string;
  data_buffer: {
    type: string
    data: Array<number>
  };
  create_time: string
}

const FilesList: React.FC = () => {
  const [files, setFiles] = useState([])
  useEffect(() => {
    async function fetchFiles() {
      const result = await request('/api/load', {
        params: {
          page: 1,
          pageSize: 10,
          keywords: ''
        }
      })
      const list = result.data?.data?.list
      setFiles(list || [])
    }
    let timer = setTimeout(() => {
      fetchFiles()
    }, 500)
    return () => clearTimeout(timer)
  }, [])
  function handleCopy(md5: string) {
    return function () {
      let input = document.createElement('input')
      input.value = `/api/load/${md5}`
      document.body.appendChild(input);
      input.select();
      try {
        document.execCommand('copy')
        message.success('/api/load/f07d743beea4c2df6805498eb2868b19')
      } catch (ex) {
        message.error('不支持复制')
      } finally {
        document.body.removeChild(input)
      }
    }
  }

  return (
    <div className={styles.filelist}>
      <Table dataSource={files} rowKey={'id'}>
        <Column title="文件名" dataIndex="file_name" key="file_name" />
        <Column
          title="文件名"
          key="file_name"
          render={(_: any, record: DataType) => (<>
            <span style={{marginRight: 5}}>{record.file_name}</span>
            <CopyOutlined onClick={handleCopy(record.md5)} />
          </>)}
        />
        <Column title="类型" dataIndex="mimetype" key="mimetype" />
        <Column title="大小" dataIndex="size" key="size" />
        <Column 
          title="上传时间" 
          key="create_time" 
          render={(_: any, record: DataType) => (<>
            <span>{new Date(record.create_time).toLocaleString()}</span>
          </>)}
        />
        <Column
          title="下载"
          key="data_buffer"
          render={(_: any, record: DataType) => (<>
            <a 
              href={`/api/load/${record.md5}`} 
              className={styles.download}
              download={`${new Date().toLocaleDateString()} ${record.file_name}`}
            ><DownloadOutlined/></a>
          </>)}
        />
      </Table>
    </div>
  )
}

export default FilesList
